<template>
  <div style="width: 100%" class="fileBox">
    <div style="width: 100%">
      <el-form class="operation">
        <div style="float: left">
          <el-button
            type="default"
            size="small"
            @click="backUp"
          ><span>上一级</span></el-button>
          <el-button
            type="primary"
            size="small"
            @click="newFloderClick"
          ><span>新建文件夹</span></el-button>
          <!-- <el-button type="danger" size="small"><span>删除</span></el-button> -->
          <el-button
            type="default"
            size="small"
            @click="uploadFile"
          ><span>上传文件</span></el-button>
        </div>
        <div class="icon" style="float: right">
          <i
            v-show="showIconTable"
            class="el-icon-menu"
            @click="clickIconTable"
          />
          <i
            v-show="showIconList"
            class="el-icon-s-unfold"
            @click="clickIconList"
          />
        </div>
      </el-form>
    </div>

    <el-dialog title="上传文件" :visible.sync="uploadFileDialog" width="40%">
      <el-upload
        ref="upload"
        class="upload-demo"
        drag
        action=""
        :http-request="uploadSectionFile"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-error="handleError"
        :before-remove="beforeRemove"
        :on-success="getFilePath"
        :headers="headers"
        :limit="3"
        :auto-upload="false"
        :data="{ currentDirectory }"
      >
        <!-- multiple -->

        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip">
          只能上传jpg/png文件，且单个上级不超过50MB
        </div>

        <!-- <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="submitUpload"
          >上传到服务器</el-button
        > -->
      </el-upload>
      <!--
      <el-upload
        class="upload-demo"
        action=""
        :http-request="uploadSectionFile"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :on-error="handleError"
        :before-remove="beforeRemove"
        :on-success="getFilePath"
        multiple
        :headers="headers"
        ref="upload"
        :limit="3"
        :auto-upload="false"
        :data="{ currentDirectory }"
      >
        <el-button slot="trigger" size="small" type="primary"
          >选取文件</el-button
        >
        <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="submitUpload"
          >上传到服务器</el-button
        >
      </el-upload> -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelUpload">取 消</el-button>
        <!-- <el-button type="primary" @click="confirmUpload">确 定</el-button> -->
        <el-button type="primary" @click="submitUpload">上 传</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="dialogTitle == '新建文件夹' ? '新建文件夹' : '上传文件'"
      :visible.sync="newFolderDialog"
      width="40%"
    >
      <el-form v-model="folderInfo">
        <el-form-item label="文件夹名称 * ">
          <el-input v-model="folderInfo.name" />
        </el-form-item>
        <!-- <el-form-item label="备注说明">
          <el-input type="textarea" v-model="folderInfo.remarks"></el-input>
        </el-form-item> -->
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelFolder">取 消</el-button>
        <el-button type="primary" @click="confirmFolder">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="重命名" :visible.sync="reNameDialog" width="40%">
      <el-input v-model="updateFileName" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="canelReName">取 消</el-button>
        <el-button type="primary" @click="confirmReName">确 定</el-button>
      </span>
    </el-dialog>

    <viewer
      ref="viewer"
      :images="images"
      class="viewer"
      style="width: 100px; boder: 1px solid red"
      @inited="inited"
    >
      <img
        v-for="(src, index) in images"
        :key="index"
        :src="src"
        class="image"
      >
    </viewer>
    <!-- <el-scrollbar style="width:100%;height: 300px"> -->

    <div class="container">
      <div
        v-for="(item, index) in fileList"
        :key="index"
        class="box"
        :class="item.active == 1 ? 'active' : ''"
        @click="changeBg(index)"
        @contextmenu="showMenu(item, index)"
        @dblclick="dbClick(item.directory, item.fileName, item.is_dir, index)"
      >
        <div class="iconBox">
          <img width="80" height="80" :src="getIconUrl(item.type)" alt="">
        </div>
        <div class="fileText">
          <span
            :title="item.fileName"
            style="
              white-space: nowrap;
              text-overflow: ellipsis;
              width: 100%;
              overflow: hidden;
              -webkit-box-orient: vertical;
              -webkit-line-clamp: 2;
              display: -webkit-box;
            "
          >{{ item.fileName }}</span>
        </div>

        <vue-context-menu
          :context-menu-data="contextMenuData"
          @downloadFile="downloadFile"
          @renameFile="renameFile"
          @deleteFile="deleteFile"
          @previewImg="previewImg"
        />
      </div>
    </div>

    <el-dialog
      title="内容预览（只是内容预览，不保证格式失真）"
      :visible.sync="preview_show"
      width="900px"
      :before-close="handleClosePreview"
    >
      <div style="border: 1px solid #eee; padding: 20px">
        <excel-view :datas="excelData" />

        <div
          class="viewHtml_box"
          style="background: white; min-height: 500px; padding: 10px"
          v-html="viewHtml.html"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="preview_show = false">取 消</el-button>
        <el-button
          type="primary"
          @click="preview_show = false"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getInfo } from '@/api/user'
import excelview from 'vue-preview'
import axios from 'axios'

import {
  insertFolder,
  getFolder,
  openDirectory,
  backUpDirectory,
  insertFile,
  deleteFolder,
  updateFileName,
  requestURL
} from '@/api/folder'
import { getToken } from '@/utils/auth'
export default {
  components: {
    'excel-view': excelview
  },
  data() {
    return {
      viewHtml: { html: '' },
      // 显示预览框
      preview_show: false,
      excelData: '',
      // contextmenu data (菜单数据)
      contextMenuData: {
        // the contextmenu name(@1.4.1 updated)
        menuName: 'demo',
        // The coordinates of the display(菜单显示的位置)
        axis: {
          x: null,
          y: null
        },
        // Menu options (菜单选项)
        menulists: [
          {
            fnHandler: 'downloadFile', // Binding events(绑定事件)
            // icoName: "el-icon-s-tools", // icon (icon图标 )
            btnName: '下载' // The name of the menu option (菜单名称)
          },
          {
            fnHandler: 'renameFile',
            // icoName: "el-icon-user",
            btnName: '重命名'
          },
          {
            fnHandler: 'deleteFile',
            // icoName: "el-icon-user",
            btnName: '删除'
          },
          {
            fnHandler: 'previewImg',
            // icoName: "el-icon-user",
            btnName: '预览'
          }
        ]
      },
      diasbleInput: true,
      fileList: [], // 文件列表数组
      showIconTable: false, // 文件是否以表格展示
      showIconList: true, // 文件是否以列表展示
      newFolderDialog: false, // 新建文件夹弹框
      reNameDialog: false, // 重命名弹框
      uploadFileDialog: false, // 上传弹框
      dialogTitle: '新建文件夹', // dialog标题
      directoryPath: '', // 上一级目录
      currentDirectory: '', // 当前目录
      folderInfo: {
        name: '', // 文件夹名字
        remarks: '' // 文件夹备注
      },
      sonIndex: 0, // 右键菜单方法接受index
      userPermissions: '', // 用户权限数组
      images: [],
      updateFileName: '',
      photo: null,
      description: '',
      productId: 0,
      // 添加头部请求
      headers: {
        Authorization: 'Bearer ' + getToken(),

        post: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      },
      uploadAction: '/adminapi/folder/insertFile',
      url: ''
    }
  },
  created() {
    this.getFolderList()
    this.getUserInfo()
  },
  methods: {
    // 图片预览数组
    pushImage(fileList) {
      const arr = []
      for (let i = 0; i < fileList.length; i++) {
        switch (fileList[i].type) {
          case 'folder':
            arr.push('1')
            break
          case 'png':
            arr.push(fileList[i].url)
            break
          case 'jpeg':
            arr.push(fileList[i].url)
            break
          case 'jpg':
            arr.push(fileList[i].url)
            break
          default:
            arr.push('1')
        }
        this.images = arr
      }
    },
    // 关闭预览框
    handleClosePreview() {
      this.preview_show = false
    },
    // 取消重命名框
    canelReName() {
      this.reNameDialog = false
    },
    // 文件重命名提交
    confirmReName() {
      // console.log(this.updateFileName);
      // console.log(this.fileList[this.sonIndex]);
      new Promise((resolve, reject) => {
        updateFileName({
          file: this.fileList[this.sonIndex],
          updateName: this.updateFileName
        }).then((response) => {
          this.reNameDialog = false
          this.selectFolder(this.currentDirectory)
        })
      })
    },
    // 鼠标选中文件改变背景颜色
    changeBg(index) {
      let num
      for (let i = 0; i < this.fileList.length; i++) {
        if (i === index) {
          num = i
        } else {
          this.fileList[i].active = 0
        }
      }
      this.fileList[num].active = 1
    },
    // 判断是否具有某某权限
    isPower(Permission) {
      for (let i = 0; i < this.userPermissions.length; i++) {
        if (this.userPermissions[i] == Permission) {
          return true
        }
      }
      return false
    },
    // 下载文件
    downloadFile() {
      // 有权限执行下载 否则提示没有权限
      if (this.isPower('download file')) {
        const url = this.fileList[this.sonIndex].url
        const name = this.fileList[this.sonIndex].fileName
        // console.log(url);
        // console.log(this.fileList);
        const x = new XMLHttpRequest()
        x.open('GET', url, true)
        x.responseType = 'blob'
        x.onload = function() {
          const urls = window.URL.createObjectURL(x.response)
          const a = document.createElement('a')
          a.href = urls
          a.download = name
          a.click()
        }
        x.send()
      } else {
        this.$message({
          type: 'error',
          message: '没有下载文件权限,请联系管理员!'
        })
      }
    },
    inited(viewer) {
      this.$viewer = viewer
    },
    // 预览图片
    previewImg() {
      if (this.isPower('preview file')) {
        if (this.fileList[this.sonIndex].type == 'folder') {
          this.$message({
            type: 'info',
            message: '文件夹不能预览!'
          })
        } else if (
          this.fileList[this.sonIndex].type == 'png' ||
          this.fileList[this.sonIndex].type == 'jpg' ||
          this.fileList[this.sonIndex].type == 'jpeg'
        ) {
          const arr = []
          arr.push(this.fileList[this.sonIndex].url)
          this.images = arr
          this.$viewer.view(0)
        } else {
          this.$message({
            type: 'info',
            message: '当前类型不支持预览!'
          })
        }
      } else {
        this.$message({
          type: 'error',
          message: '没有预览权限,请联系管理员!'
        })
      }
    },
    // 点击重命名按钮方法
    renameFile() {
      if (this.isPower('rename file')) {
        this.reNameDialog = true
        this.updateFileName = this.fileList[this.sonIndex].fileName
      } else {
        this.$message({
          type: 'error',
          message: '没有重命名权限,请联系管理员!'
        })
      }
    },
    // 右键菜单删除文件
    deleteFile() {
      if (this.isPower('delete file')) {
        this.$confirm('确认删除该文件吗?', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          new Promise((resolve, reject) => {
            deleteFolder({ file: this.fileList[this.sonIndex] }).then(
              (response) => {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
                this.selectFolder(this.currentDirectory)
              }
            )
          })
        })
      } else {
        this.$message({
          type: 'error',
          message: '没有删除权限,请联系管理员!'
        })
      }
    },
    // uploadFile(){
    //   console.log(4);
    // },
    // 打开右键菜单
    showMenu(item, index) {
      this.sonIndex = index // 子组件存储下表
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      this.contextMenuData.axis = {
        x,
        y
      }
      let num
      // 点击当前文件 添加active 属性 添加样式
      for (let i = 0; i < this.fileList.length; i++) {
        if (i === index) {
          num = i
        } else {
          this.fileList[i].active = 0
        }
      }
      this.fileList[num].active = 1
    },

    // 上传文件到当前目录
    uploadSectionFile(param) {
      const formData = new FormData()
      formData.append('file', param.file)
      formData.append('currentDirectory', this.currentDirectory)
      new Promise((resolve, reject) => {
        insertFile(formData)
          .then((response) => {
            param.onSuccess(response.data)
            this.uploadFileDialog = false
            // 上传成功后查询当前目录文件和子目录
            this.$refs.upload.clearFiles()
            this.selectFolder(this.currentDirectory)
          })
          .catch((err) => {
            this.handleRemove(param.file)
          })
      })
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    // 获取文件返回路径
    getFilePath(res) {
      this.$message({
        type: 'success',
        message: '上传成功!'
      })
    },
    // 提交上传弹窗
    confirmUpload() {
      this.uploadFileDialog = false
      // 取消当前上传文件的列表
      this.$refs.upload.clearFiles()
    },
    // 取消上传弹窗
    cancelUpload() {
      this.uploadFileDialog = false
      this.$refs.upload.clearFiles()
    },
    // 上传方法
    uploadFile() {
      this.uploadFileDialog = true
      // if (this.directoryPath == "/") {
      // }
    },
    // 返回上一级方法
    backUp() {
      if (this.directoryPath == '/') {
        this.$message({
          type: 'info',
          message: '已经在最上级了!'
        })
      } else {
        this.selectFolder(this.directoryPath)
      }
    },

    // 根据路径查询文件列表
    selectFolder(directory) {
      // console.log(directory);
      // if(directory == "" || directory==null){
      //   return null
      // }
      return new Promise((resolve, reject) => {
        backUpDirectory({ directory: directory }).then((response) => {
          this.fileList = response.data
          if (this.fileList == null || this.fileList == '') {
            return null
          }
          // 截取掉  / 后面的内容
          this.directoryPath = this.fileList[0].directory.substring(
            this.fileList[0].directory.lastIndexOf('/'),
            -1
          )
          this.pushImage(this.fileList)
          // 如果当前目录为空 让上一级目录变为  /
          if (this.directoryPath == null || this.directoryPath == '') {
            this.directoryPath = '/'
          }
          this.currentDirectory = this.fileList[0].directory
        })
      })
    },
    // 双击事件
    dbClick(directory, fileName, is_dir, index = 0) {
      // console.log(directory, fileName, is_dir);
      // 判断是否是文件夹
      if (is_dir == '1') {
        new Promise((resolve, reject) => {
          openDirectory({ directory: directory, fileName: fileName }).then(
            (response) => {
              this.fileList = response.data
              this.directoryPath = directory
              this.currentDirectory = directory + '/' + fileName
              this.pushImage(this.fileList)
            }
          )
        })
      }
      if (is_dir == '2') {
        if (
          this.fileList[index].type == 'png' ||
          this.fileList[index].type == 'jpg' ||
          this.fileList[index].type == 'jpeg'
        ) {
          // console.log(this.fileList[this.sonIndex].url);
          const arr = []
          arr.push(this.fileList[index].url)
          this.images = arr

          this.$viewer.view(0)
        } else if (
          this.fileList[index].type == 'doc' ||
          this.fileList[index].type == 'docx'
        ) {
          var mammoth = require('mammoth')

          // mammoth
          //   .convertToHtml({ path: this.fileList[index].url })
          //   .then(function (result) {
          //     var html = result.value; // The generated HTML
          //     var messages = result.messages; // Any messages, such as warnings during conversion
          //   })
          //   .done();
          const _self = this
          const xhr = new XMLHttpRequest()
          xhr.open('get', this.fileList[index].url, true)
          // xhr.open("get", "/fileManagement/4/大成备注.docx", true);
          // xhr.open("get", "/fileManagement/4/锐晶(1).docx", true);
          xhr.responseType = 'arraybuffer'
          xhr.onload = function() {
            if (xhr.status == 200) {
              var options = {
                styleMap: [
                  "p[style-name='Section Title'] => h1:fresh",
                  "p[style-name='Subsection Title'] => h2:fresh",
                  'b => em',
                  'i => strong',
                  'strike => del',
                  'comment-reference => sup'
                ],
                convertImage: mammoth.images.imgElement(function(image) {
                  return image.read('base64').then(function(imageBuffer) {
                    return {
                      src:
                        'data:' + image.contentType + ';base64,' + imageBuffer
                    }
                  })
                })
              }

              mammoth
                .convertToHtml(
                  { arrayBuffer: new Uint8Array(xhr.response) },
                  options
                )
                .then(function(resultObject) {
                  _self.preview_show = true

                  _self.$set(_self.viewHtml, 'html', resultObject.value)

                  // _self.$nextTick(() => {
                  //   // document.querySelector("#wordView").innerHTML =
                  //   //   resultObject.value;

                  //   _self.$set(this.viewHtml,'html', resultObject.value)
                  // });
                })
            }
          }
          xhr.send()
        } else if (
          this.fileList[index].type == 'xlsx' ||
          this.fileList[index].type == 'xls'
        ) {
          axios
            .get(this.fileList[index].url, {
              responseType: 'arraybuffer'
            })
            .then((res) => {
              this.preview_show = true
              this.excelData = res.data
            })
        } else {
          this.$message({
            type: 'info',
            message: '当前类型文件不支持预览!'
          })
        }
      }
    },

    // 根据返回的数据类型显示不同的图片
    getIconUrl(type) {
      const arr = [
        'png',
        'ppt',
        'jpg',
        'jpeg',
        'docx',
        'php',
        'index',
        'html',
        'zip',
        'rar',
        'xlsx',
        'txt',
        'text',
        'folder'
      ]
      let flag = ''
      for (let i = 0; i < arr.length; i++) {
        if (type == arr[i]) {
          flag = true
        }
      }
      if (flag == true) {
        return require('@/assets/resourse/' + type + '.png')
      } else {
        return require('@/assets/resourse/' + 'none' + '.png')
      }
    },

    // 获取文件夹和目录列表
    getFolderList() {
      new Promise((resolve, reject) => {
        getFolder().then((response) => {
          this.fileList = response.data
          this.directoryPath = '/'
          // console.log("file");
          // console.log(this.fileList);
          if (this.fileList == null || this.fileList == '') {
            this.currentDirectory = '/fileManagement'
          } else {
            this.currentDirectory = this.fileList[0].directory
          }
        })
      })
    },

    // 取消dialog
    cancelFolder() {
      this.newFolderDialog = false
      this.folderInfo.name = ''
      this.folderInfo.remarks = ''
    },
    // 提交文件夹信息
    confirmFolder() {
      // console.log(this.dialogTitle);
      // console.log(this.currentDirectory);
      if (this.dialogTitle == '新建文件夹') {
        new Promise((resolve, reject) => {
          insertFolder({
            folderInfo: this.folderInfo,
            directory: this.currentDirectory
          }).then((response) => {
            this.$message({
              type: 'success',
              message: '新建文件夹成功!'
            })
            this.newFolderDialog = false
            this.folderInfo.name = ''
            this.folderInfo.remarks = ''
            this.selectFolder(this.currentDirectory)
          })
        })
      } else {
      }
    },
    // 点击新建文件夹按钮
    newFloderClick() {
      if (this.isPower('insert file')) {
        this.dialogTitle = '新建文件夹'
        this.newFolderDialog = true
      } else {
        this.$message({
          type: 'error',
          message: '没有新建文件夹权限,请联系管理员!'
        })
      }
    },
    // 将文件以列表展示
    clickIconList() {
      this.showIconList = !this.showIconList
      this.showIconTable = !this.showIconTable
    },
    // 将文件以表格类型显示
    clickIconTable() {
      this.showIconTable = !this.showIconTable
      this.showIconList = !this.showIconList
    },
    // 上传失败
    handleError(err, file, fileList) {
      // console.log(err);
      this.$message({
        type: 'error',
        message: '上传失败,请重新上传!'
      })
    },
    // 下载
    handleDownload($index, row) {},
    // 文件预览
    handlePreview() {},
    // 文件移除
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    // 文件限制
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      )
    },
    // 文件移除前
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 获取当前用户的登录信息
    getUserInfo() {
      new Promise((resolve, reject) => {
        getInfo().then((response) => {
          // console.log("info");
          // console.log(response.data);
          // this.username = response.data.name; //当前登录用户的姓名
          this.userPermissions = response.data.per // 当前登录用户权限数组
          // console.log(this.userPermissions);
        })
      })
    }
  }
}
</script>

<style>
.fileBox .container {
  /* width: 100%; */
  margin: 10px;
  /* border: 1px solid red; */
  display: grid;
  grid-row-gap: 20px;
  grid-column-gap: 20px;
  grid-template-columns: repeat(auto-fill, 100px);
  /* grid-template-rows: repeat(auto-fill, 100px); */
}

.fileBox .container .box {
  /* border: 1px solid red; */
  width: 112px;
  height: 136px;
  margin: 5px;
  padding: 10%;
}
.fileBox .container .box .iconBox {
  width: 100%;
  height: 80px;
  text-align: center;
}

.fileBox .container .box .fileText {
  width: 100%;
  margin-top: 10px;
  text-align: center;
  height: 23px;
  line-height: 23px;
  color: #595c5f;
  font-size: 15px;
}
.fileInput .el-input__inner {
  text-align: center;
  height: 25px;
  margin-top: 5px;
  border: none;
}
.tableList {
  margin: 10px;
}

.el-dialog .el-dialog__body {
  padding: 0px 20px 10px 20px;
}
.el-form-item__content .el-input .el-input__inner {
  height: 30px;
  line-height: 30px;
}
.el-form-item {
  margin-bottom: 10px;
}
.operation {
  padding: 10px;
  margin: 10px;
  width: 100%;
  margin-right: 10px;
  display: inline-block;
  -webkit-box-shadow: 6px 6px 15px rgba(0, 0, 0, 0.3);
  box-shadow: 6px 6px 15px rgba(0, 0, 0, 0.3);
}
.icon {
  font-size: 20px;
  cursor: pointer;
  color: #00abea;
  line-height: 32px;
  padding-right: 30px;
}
.box .vue-contextmenuName-demo {
  margin: 0;
  padding: 0;
  width: 130px;
  text-align: center;
}
.box .vue-contextmenuName-demo .btn-wrapper-simple {
  height: 30px;
  line-height: 30px;
  align-items: center;
}
.box .nav-name-right {
  font-size: 14px;
  font-family: "微软雅黑";
  color: #333;
  text-align: center;
  line-height: 20px;
  display: block;
}
.box .context-menu-list :hover {
  background: #ccc;
}
.el-input.is-disabled .el-input__inner {
  background: none;
  color: #595c59;
}
.active {
  background: #eff3f9 none repeat scroll 0 0;
  border-color: #bcccde;
  border-radius: 10px;
}
.fileBox .image {
  display: none;
}

.viewHtml_box img {
  max-width: 100%;
}
</style>
